package com.knowledgegraph.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.knowledgegraph.common.Result;
import com.knowledgegraph.entity.KnowledgeGraph;
import com.knowledgegraph.security.UserPrincipal;
import com.knowledgegraph.service.KnowledgeGraphService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 知识图谱控制器
 * 
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/knowledge-graph")
@Validated
public class KnowledgeGraphController {

    @Autowired
    private KnowledgeGraphService knowledgeGraphService;

    /**
     * 创建知识图谱
     */
    @PostMapping("/create")
    @PreAuthorize("hasRole('USER')")
    public Result<KnowledgeGraph> createGraph(@Valid @RequestBody KnowledgeGraph knowledgeGraph,
                                            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            boolean success = knowledgeGraphService.createGraph(knowledgeGraph, userPrincipal.getId());
            if (success) {
                return Result.success("创建成功", knowledgeGraph);
            } else {
                return Result.error("创建失败");
            }
        } catch (Exception e) {
            log.error("创建知识图谱失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新知识图谱
     */
    @PostMapping("/update")
    @PreAuthorize("hasRole('USER')")
    public Result<String> updateGraph(@RequestBody Map<String, Object> params,
                                    @AuthenticationPrincipal UserPrincipal userPrincipal) {
        
        Long id = Long.valueOf(params.get("id").toString());
        @SuppressWarnings("unchecked")
        Map<String, Object> graphData = (Map<String, Object>) params.get("knowledgeGraph");
        
        KnowledgeGraph knowledgeGraph = new KnowledgeGraph();
        // 设置基本属性，根据实际KnowledgeGraph实体类调整
        knowledgeGraph.setName((String) graphData.get("name"));
        knowledgeGraph.setDescription((String) graphData.get("description"));
        try {
            knowledgeGraph.setId(id);
            boolean success = knowledgeGraphService.updateGraph(knowledgeGraph, userPrincipal.getId());
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新知识图谱失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除知识图谱
     */
    @PostMapping("/delete")
    @PreAuthorize("hasRole('USER')")
    public Result<String> deleteGraph(@RequestBody Map<String, Object> params,
                                    @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Long id = Long.valueOf(params.get("id").toString());
        try {
            boolean success = knowledgeGraphService.deleteGraph(id, userPrincipal.getId());
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除知识图谱失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取知识图谱详情
     */
    @PostMapping("/detail")
    public Result<KnowledgeGraph> getGraph(@RequestBody Map<String, Object> params,
                                         @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Long id = Long.valueOf(params.get("id").toString());
        try {
            KnowledgeGraph graph = knowledgeGraphService.getById(id);
            if (graph == null) {
                return Result.notFound();
            }
            
            // 检查权限
            if (!knowledgeGraphService.hasGraphPermission(id, userPrincipal.getId())) {
                return Result.forbidden();
            }
            
            return Result.success(graph);
        } catch (Exception e) {
            log.error("获取知识图谱详情失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取我的知识图谱列表
     */
    @PostMapping("/my")
    @PreAuthorize("hasRole('USER')")
    public Result<List<KnowledgeGraph>> getMyGraphs(@AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            List<KnowledgeGraph> graphs = knowledgeGraphService.getGraphsByCreator(userPrincipal.getId());
            return Result.success(graphs);
        } catch (Exception e) {
            log.error("获取我的知识图谱列表失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页获取公开知识图谱
     */
    @PostMapping("/public")
    public Result<Page<KnowledgeGraph>> getPublicGraphs(@RequestBody Map<String, Object> params) {
        
        Integer current = (Integer) params.getOrDefault("current", 1);
        Integer size = (Integer) params.getOrDefault("size", 10);
        try {
            Page<KnowledgeGraph> page = new Page<>(current, size);
            Page<KnowledgeGraph> result = (Page<KnowledgeGraph>) knowledgeGraphService.getPublicGraphs(page);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取公开知识图谱失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 搜索知识图谱
     */
    @PostMapping("/search")
    public Result<Page<KnowledgeGraph>> searchGraphs(@RequestBody Map<String, Object> params) {
        
        String keyword = (String) params.get("keyword");
        Integer current = (Integer) params.getOrDefault("current", 1);
        Integer size = (Integer) params.getOrDefault("size", 10);
        try {
            Page<KnowledgeGraph> page = new Page<>(current, size);
            Page<KnowledgeGraph> result = (Page<KnowledgeGraph>) knowledgeGraphService.searchGraphs(keyword, page);
            return Result.success(result);
        } catch (Exception e) {
            log.error("搜索知识图谱失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取统计信息
     */
    @PostMapping("/statistics")
    @PreAuthorize("hasRole('USER')")
    public Result<Map<String, Object>> getStatistics(@AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            Map<String, Object> statistics = knowledgeGraphService.getGraphStatistics(userPrincipal.getId());
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取统计信息失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新图谱统计数据
     */
    @PostMapping("/update-statistics")
    @PreAuthorize("hasRole('USER')")
    public Result<String> updateStatistics(@RequestBody Map<String, Object> params,
                                         @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Long id = Long.valueOf(params.get("id").toString());
        try {
            // 检查权限
            if (!knowledgeGraphService.hasGraphPermission(id, userPrincipal.getId())) {
                return Result.forbidden();
            }
            
            knowledgeGraphService.updateGraphStatistics(id);
            return Result.success("统计数据更新成功");
        } catch (Exception e) {
            log.error("更新统计数据失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
}